<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="utf-8">
  <title>腕带类型管理</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <script th:src="@{/plugin/jquery/jquery-3.4.1.js}" charset="utf-8"></script>
  <link rel="stylesheet" th:href="@{/plugin/layui/css/layui.css}">
  <script type="text/javascript" th:src="@{/plugin/layui/layui.js}"></script>
</head>

<body style="padding: 20px;">
  <!-- 页面结构 -->
  <div class="layui-main">
    <!-- 表格上方标题 -->
    <blockquote class="layui-elem-quote" >腕带类型列表</blockquote>
    <!-- 添加按钮 -->
    <a class="layui-btn layui-btn-sm" id="add-wtype-btn" lay-event=""  >添加腕带类型</a>
    <!--腕带类型表 -->
    <table id="wtype-tbl" lay-filter="wtype-tbl"  ></table>
	
    <script type="text/html" id="wtype-tbl-toolbar">
      <a class="layui-btn layui-btn-xs" lay-event="updateWType">编辑</a>
      <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="deleteWType">删除</a>
    </script>
  </div>
  
  <!-- 添加腕带类型弹出层 -->
  <div id="add-wtype-layer" style="display: none; padding: 20px">
    <form id="add-wtype-form" class="layui-form layui-form-pane">
      <div class="layui-form-item">
        <label class="layui-form-label" >腕带类型名称</label>
        <div class="layui-input-block">
          <input type="text" id="add_type_name" name="type_name" class="layui-input" lay-verify="required" autocomplete="off">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">可否消费</label>
        <div class="layui-input-block">
        	<input type="radio" name="add_consumable" value="YES" title="YES" >
			<input type="radio" name="add_consumable" value="NO" title="NO" checked>
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label" >可否充值</label>
        <div class="layui-input-block">
        	<input type="radio" name="add_rechargeable" value="YES" title="YES" lay-verify="required">
			<input type="radio" name="add_rechargeable" value="NO" title="NO" checked>
        </div>
      </div>
	  <div class="layui-form-item">
	  	<label class="layui-form-label">可否授权</label>
	    <div class="layui-input-inline">
			<input type="radio" name="add_authorized" value="YES" title="YES" lay-verify="required">
			<input type="radio" name="add_authorized" value="NO" title="NO" checked>
	    </div>
	  </div>
	  <div class="layui-form-item">
	  	<label class="layui-form-label">最小预存金额</label>
	    <div class="layui-input-inline">
			<input type="text" id="add_minimum" name="minimum" class="layui-input" lay-verify="required|number" autocomplete="off">
	    </div>
	  </div>
	  <div class="layui-form-item">
	  	<label class="layui-form-label">最大预存金额</label>
	    <div class="layui-input-inline">
			<input type="text" id="add_maximum" name="maximum" class="layui-input" lay-verify="required|number" autocomplete="off">
	    </div>
	  </div>
	  <div class="layui-form-item">
	  	<label class="layui-form-label">折扣度</label>
	    <div class="layui-input-inline">
			<input type="text" id="add_discount" name="discount" class="layui-input" lay-verify="required|number|discount" autocomplete="off">
	    </div>
	  </div>
	  <div class="layui-form-item">
	 	<label class="layui-form-label">所属组织</label>
	    <div class="layui-input-inline">
			<select id="add-org" name="organization_id" class="select">
				
			</select>
	    </div>
	  </div>
	  <div class="layui-form-item">
	 	<label class="layui-form-label">选择消费项</label>
	    <div class="layui-input-block" id="items">
			
	    </div>
	  </div>
      <div class="layui-form-item">
        <div class="layui-input-block " >
          <button class="layui-btn" lay-submit lay-filter="add-wtype-form-submit">提交</button>
          <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
      </div>
    </form>
  </div>
  
  <!-- 更新腕带类型弹出层 -->
  <div id="update-wtype-layer" style="display: none; padding: 20px">
    <form id="update-wtype-form" class="layui-form layui-form-pane" lay-filter="update-wtype-form">
      <div class="layui-form-item" >
        <label class="layui-form-label">序号</label>
        <div class="layui-input-block">
          <input type="text" name="id" id="up_type_id" class="layui-input" readonly>
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">腕带类型名称</label>
        <div class="layui-input-block">
          <input type="text" name="type_name" id="up_type_name" class="layui-input" lay-verify="required" autocomplete="off" >
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">可消费</label>
        <div class="layui-input-block">
          	<input type="radio" id="cy" name="up_consumable" value="YES" title="YES" >
			<input type="radio" id="cn" name="up_consumable" value="NO" title="NO" checked>
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">可充值</label>
        <div class="layui-input-block">
        	<input type="radio" id="ry" name="up_rechargeable" value="YES" title="YES" >
			<input type="radio" id="rn" name="up_rechargeable" value="NO" title="NO" checked>
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">可授权</label>
	    <div class="layui-input-inline">
			<input type="radio" id="ay" name="up_authorized" value="YES" title="YES" >
			<input type="radio" id="an" name="up_authorized" value="NO" title="NO" checked>
	    </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">最小预存金额</label>
        <div class="layui-input-block">
          <input type="text" name="minimum" id="up_minimum" class="layui-input" lay-verify="required|number" autocomplete="off" >
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">最大预存金额</label>
        <div class="layui-input-block">
          <input type="text" name="maximum" id="up_maximum" class="layui-input" lay-verify="required|number" autocomplete="off" >
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">折扣度</label>
        <div class="layui-input-block">
          <input type="text" name="discount" id="up_discount" class="layui-input" lay-verify="required|number|discount" autocomplete="off" >
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">消费项</label>
        <div class="layui-input-block" id="up_items">
        	
        </div>
      </div>     
	  <div class="layui-form-item">
	    <label class="layui-form-label">所属组织</label>
	    <div class="layui-input-inline">
			<select id="up_org" name="organization.organization_id" class="select">
				
			</select>
	    </div>
	  </div>
      <div class="layui-form-item">
        <div class="layui-input-block">
          <button class="layui-btn" lay-submit lay-filter="update-wtype-form-submit">提交</button>
        <!--  <button type="reset" class="layui-btn layui-btn-primary">重置</button> -->
        </div>
      </div>
    </form>
  </div>
  <!-- 页面JS -->
  <script>
    layui.use(['jquery', 'table', 'layer', 'form'], function() {
      // 加载layui模块，使用其推荐的【预先加载】方式，详见官网【模块规范】一节
      var $ = layui.$;
      var table = layui.table;
      var layer = layui.layer;
      var form = layui.form;
      
      // 自定义验证规则
      form.verify({
      	discount: [
      		/^(1|0(\.\d{1,2})?)$/
      	    ,'请填入0.01-1的数字,保留两位小数'
      	  ] 
     	})
      
      // 显示所有腕带类型
      table.render({
        elem: '#wtype-tbl',
        url: '[[@{/wriststrpType/getall}]]',//请求地址
        method: 'get',
        cols: [ [
         // {type:'checkbox',title:"选择"},
          {field: 'type_id', title: '序号',sort:true,width:75},
          {field: 'type_name', title: '腕带类型',width:90},
          {field: 'consumable', title: '可消费',width:80},
          {field: 'rechargeable', title: '可充值',width:80},
          {field: 'authorized', title: '可授权',width:80},
          {field: 'minimum', title: '最小预存',width:88},
          {field: 'maximum', title: '最大预存',width:88},
          {field: 'create_time', title: '创建时间',width:135,templet:function(data){
        	  if(data.create_time != null){
        		  return showDate(data.create_time);
        	  }
          }},
          {field: 'discount', title: '折扣',width:60},
          {field: 'items', title: '消费项',templet:function(data){
        	  if(data.items != null){
        		  var arr = new Array();
        		  // 遍历消费项，赋值给数组
        		  for(var i=0; i<data.items.length; i++){
        			  arr[i] = data.items[i].consumer_item_name;
        		  }
        		  return arr.join("|");
        	  }
          }},
          {templet:function(data){
        	  return data.organization.organization_name;
          },title:'所属组织'},
          
          {toolbar: '#wtype-tbl-toolbar', title: '操作'}
        ] ],
        // 表格容器id，用于表格重载
        id: 'wtype-tbl',
      });
      
      // 显示添加腕带类型弹出层
      $('#add-wtype-btn').click(function() {
        // 每次显示前重置表单
        $('#add-wtype-form')[0].reset();
        // 更新下拉菜单和选择框
        querySelect();
        // 显示模态框
        layer.open({
          type: 1,
          title: '添加腕带类型',
          skin: 'layui-layer-molv',
          area: ['1000px'],
          content: $('#add-wtype-layer')
        });
      });
      //

      // 添加腕带类型表单提交
      form.on('submit(add-wtype-form-submit)', function(data) {
    	// 判断折扣是否在合适范围
    	if($("#add_discount").val()<=0||$("#add_discount").val()>1){
    		layer.msg("折扣度范围错误，折扣度:在0.01-1.00之间");
    		return;
    	}
    	// 遍历获取复选框的值
    	//获取checkbox[name='citem']的值
        var arr = new Array();
        $("input:checkbox[name='citem']:checked").each(function(i){
        	arr[i] = $(this).val();
      });
        // ajax方式添加腕带类型
        $.ajax({
          url: "[[@{/wriststrpType/insertOne}]]",
          type: "POST",
          data: {
        	 type_name:$("#add_type_name").val(),
        	 consumable:$('input[name="add_consumable"]:checked ').val(),
        	 rechargeable:$('input[name="add_rechargeable"]:checked ').val(),
        	 authorized:$('input[name="add_authorized"]:checked ').val(),
        	 minimum:$("#add_minimum").val(),
        	 maximum:$("#add_maximum").val(),
        	 discount:$("#add_discount").val(),
             "organization.organization_id":$("#add-org").val(),
             itemstr:arr.join(",")
          },
          //contentType: 'application/json',
          dataType: 'json',
          success: function(data) {
            if (data.code == 1) {
              layer.close(layer.index);
              layer.msg(data.msg);
              table.reload('wtype-tbl');
            } else {
              layer.msg(data.msg);
            }
          },
          error: function() {
            console.log("ajax error");
          }
        });
        // 阻止表单跳转
        return false;
      });
      
      // 监听行工具栏事件：删除腕带类型与更新腕带类型
      table.on('tool(wtype-tbl)', function(obj) {
        // 获取当前行数据和lay-event的值
        var data = obj.data;
        var event = obj.event;
        
        // 删除腕带类型事件
        if (event === 'deleteWType') {
          layer.confirm('确定删除该腕带类型吗？', function(index) {
            // ajax方式删除腕带类型
            $.ajax({
              url:'[[@{/wriststrpType/deleteOne}]]',
              type: "POST",
              data:{
              	type_id:data.type_id  
              },
              dataType: 'json',
              success: function(data) {
                if (data.code == 1) {
                  layer.msg(data.msg);
                  table.reload('wtype-tbl');
                } else {
                  layer.msg(data.msg);
                }
              },
              error: function() {
                console.log("ajax error");
              }
            });
            layer.close(index);
          });
        }
        
        // 更新事件 修改
        if (event === 'updateWType') {
          // 更新下拉选项列
          querySelect();
          // 每次显示更新腕带类型的表单前自动为表单填写该行的数据
          form.val('update-wtype-form', {
          	"id": data.type_id,
           	"type_name": data.type_name,
           	"minimum": data.minimum,
          	"maximum": data.maximum,
          	"maximum": data.maximum,
          	"discount": data.discount,
        	"organization.organization_id": data.organization.organization_id
          });
          // 为单选框赋原始值
          switch(data.consumable){
          	case "YES":
          		$("#cy").prop("checked",true);
          		break;
          	case "NO":
          		$("#cn").prop("checked",true);
          		break;
          	default:
          		break;
          }
          switch(data.rechargeable){
        	case "YES":
        		$("#ry").prop("checked",true);
        		break;
        	case "NO":
        		$("#rn").prop("checked",true);
        		break;
        	default:
        		break;
        }
        switch(data.authorized){
     	 	case "YES":
      			$("#ay").prop("checked",true);
      			break;
      		case "NO":
      			$("#an").prop("checked",true);
      			break;
      		default:
      			break;
     	 }
        // 为复选框赋值
        $("input[name='uitem']").each(function(index,ele){
        	var nowid = $(this).val();
        	for(var i=0;i<data.items.length;i++){
        		if(data.items[i].consumer_item_id == nowid){
        			$(this).prop('checked',true);
        		}
        	}
		});
          // 再次渲染，防止上一步更新的单选框不显示。
          form.render();
          // 显示更新腕带类型表单的弹出层
          layer.open({
            type: 1,
            title: '修改',
            skin: 'layui-layer-molv',
            area: ['1000px'],
            content: $('#update-wtype-layer')
          });
          // 更新腕带类型表单提交
          form.on('submit(update-wtype-form-submit)',function(data) {
        	  // 获取消费项复选框的所有值
        	  var arr = new Array();
        	  	$("input:checkbox[name='uitem']:checked").each(function(i){
        	    	arr[i] = $(this).val();
        	    });	  
            // ajax方式更新腕带类型
            $.ajax({
              url:"[[@{/wriststrpType/updateOne}]]",
              type:"POST",
              data:{
            	  type_id:$("#up_type_id").val(),
            	  type_name:$("#up_type_name").val(),
             	  consumable:$('input[name="up_consumable"]:checked ').val(),
             	  rechargeable:$('input[name="up_rechargeable"]:checked ').val(),
             	  authorized:$('input[name="up_authorized"]:checked ').val(),
             	  minimum:$("#up_minimum").val(),
             	  maximum:$("#up_maximum").val(),
             	  discount:$("#up_discount").val(),
                  "organization.organization_id":$("#up_org").val(),
                  itemstr:arr.join(",")
              },
              dataType:'json',
              success:function(data) {
                if (data.code == 1) {
                  layer.close(layer.index);
                  layer.msg(data.msg);
                  table.reload('wtype-tbl');
                } else {
                  layer.msg(data.msg);
                }
              },
              error: function() {
                console.log("ajax error");
              }
            });
            // 阻止表单跳转
            return false;
          });
        }
      });
    });
    //更新本页所有组织下拉选项
    function querySelect(){
    	var text ="";
    	var updateText ="";
    	// 更新消费项 复选框的所有选择项
        	$.ajax({
	            type:"POST",
	            url:'[[@{/consumeritem/getall}]]',  //从数据库查询所有消费项
	            dataType: "json",
	            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
	            async: false,
	            cache: false,
	            success: function (data) {
	            	for(var i=0;i<data.data.length;i++){
	            		text += "<input type='checkbox' name='citem' value='"+data.data[i].consumer_item_id+
	            		"' title='"+data.data[i].consumer_item_name+"' />";
	            		updateText += "<input type='checkbox' name='uitem' value='"+data.data[i].consumer_item_id+
	            		"' title='"+data.data[i].consumer_item_name+"' />";
	            	}
	                $("#items").html(text);   
	                $("#up_items").html(updateText);
	            }
	           
       		});
    	// 更新组织下拉框
        var org = "";
        	$.ajax({
	            type:"POST",
	            url:'[[@{/organization/getAll.do}]]',  //从数据库查询所有组织
	            dataType: "json",
	            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
	            async: false,
	            cache: false,
	            success: function (data) {
	            	for(var i=0;i<data.length;i++){
	            		org += "<option value="+data[i].organization_id+">"+data[i].organization_name+"</option>";
	            	}
	                $("#up_org").html(org); 
	                $("#add-org").html(org);
	            } 
       		});
    }
    
    // 自定义时间展示函数
    function showDate(stime){
    	var date = new Date(stime);
    	var y = date.getFullYear();
    	var m = date.getMonth()+1;
    	m = M<10? ('0'+m):m;
    	var d = date.getDate();
    	d = d<10?("0"+d):d;
    	var h = date.getHours();
    	h = h<10?("0"+h):h;
    	var M = date.getMinutes();
    	M = M<10?("0"+M):M;
    	var str = y+"-"+m+"-"+d+" "+h+":"+M;
    	return str;
    }
  </script>
</body>

</html>